<?php

// $Id$

require_once($WSC->get_site_inc_dir().'modules/tangra_cms/classes/ci/tcms_ci_type_attr_dbc.class.php');
require_once($WSC->get_site_inc_dir().'modules/tangra_cms/classes/ci/tcms_ci_attr_type_dbc.class.php');
require_once($WSC->get_site_inc_dir().'modules/tangra_cms/classes/ci/tcms_ci_dbc.class.php');
require_once($WSC->get_site_inc_dir().'modules/tangra_cms/classes/ci/tcms_ci_type_dbc.class.php');
require_once($WSC->get_site_inc_dir().'modules/tangra_cms/classes/ci/tcms_ci_mod_dbc.class.php');
require_once($WSC->get_site_inc_dir().'modules/tangra_cms/classes/vpage/tcms_vpage_ci_dbc.class.php');
require_once($WSC->get_site_inc_dir().'modules/tangra_cms/classes/vpage/tcms_vpage_dbc.class.php');


class TCMS_CI_Deleter extends Tangra_Class {
	public static function delete(DB_Connection $dbc, $ci_id, $hidden_inc_dir, $current_user_id) {
		TCMS_CI_Deleter::delete_ci_links_to_vpages($dbc, $ci_id, $current_user_id);

		$ci = new TCMS_CI_DBC();
		if ($ci->load_by_id($dbc, $ci_id)) {
			$ci_type = new TCMS_CI_Type_DBC();
			if ($ci_type->load_by_id($dbc, $ci->get_type())) {
				$attr_type_ids = TCMS_CI_Type_Attr_DBC::select_distinct_attr_type_ids_for_ci_type($dbc, $ci_type->get_id());
				foreach($attr_type_ids as $attr_type_id) {
					TCMS_CI_Deleter::delete_cias_for_ci_and_type($dbc, $ci_id, $attr_type_id, $hidden_inc_dir);
				}
			}

			TCMS_CI_DBC::delete($dbc, $ci_id);
		}
	}


	private static function delete_cias_for_ci_and_type(DB_Connection $dbc, $ci_id, $ciat_id,  $hidden_inc_dir) {
		$ciat = new TCMS_CI_Attr_Type_DBC();
		if ($ciat->load_by_id($dbc, $ciat_id)) {
			$class_name = $ciat->get_class_name();
			if (!class_exists($class_name)) {
				require_once($hidden_inc_dir.$ciat->get_class_path());
			}

			$cia = new $class_name();
			$cia->delete_all_for_ci($dbc, $ci_id);
		}
	}


	private static function delete_ci_links_to_vpages(DB_Connection $dbc, $ci_id, $current_user_id) {
		TCMS_VPage_DBC::update_last_modified_for_ci($dbc, $ci_id, $current_user_id);
		TCMS_VPage_CI_DBC::delete_all_for_ci($dbc, $ci_id);
	}
}


